#include "wblib.h"
#include "NUC900_spi.h"

#define SPI_BUFFER_SIZE	2048
__align(4096) UINT8 spiFlash_Buf[SPI_BUFFER_SIZE];
__align(4096) UINT8 spiReadBackBuffer[SPI_BUFFER_SIZE];


int diag_spi()
{
	int status;
	int volatile i;
	WB_PLL_T sysClock;

	sysprintf("\nTest SPI flash ...\n");
	sysprintf("Please check the SPI switch...\n");
	sysprintf("It should turn ON...\n");
	sysprintf("\n\nPress any key to begin test...\n");
	sysGetChar();

	sysClock.pll0 = PLL_200MHZ;
	sysClock.pll1 = PLL_133MHZ;
	sysClock.cpu_src = CPU_FROM_PLL0;
	sysClock.ahb_clk = AHB_CPUCLK_1_2;
	sysClock.apb_clk = APB_AHB_1_2;
	sysSetPLLConfig(&sysClock);

#if 1
	sysDisableCache();
	sysInvalidCache();
	sysEnableCache(CACHE_WRITE_BACK);
#endif

	spiIoctl(SPI_SET_CLOCK, 50);
	status = spiOpen();
	if (status < 0)
		return status;

	/* build test pattern */
	for (i=0; i<SPI_BUFFER_SIZE; i++)
		spiFlash_Buf[i] = i;

	sysprintf("write\n");
	spiWrite(0, SPI_BUFFER_SIZE, (INT32)spiFlash_Buf);

	sysprintf("read\n");
	spiRead(0, SPI_BUFFER_SIZE, (INT32)spiReadBackBuffer);

	sysprintf("compare\n");
	for (i=0; i<SPI_BUFFER_SIZE; i++)
	{
		if (spiReadBackBuffer[i] != spiFlash_Buf[i])
		{
			sysprintf("error! [%d]->wrong[%x] / correct[%x]\n", i, spiReadBackBuffer[i], spiFlash_Buf[i]);
			break;
		}
	}

	sysprintf("finish..\n");

	return 0;
}

